import "./css/flatpickr.min.css"
import "./css/mobile.css"
import "./js/flatpickr.min.js"
import "./js/flatpickr.zh.js"
import { marked } from 'marked';
import { 排盘 } from '../src/bazi.ts';

// ==================== 常量定义 ====================

// 天干地支五行映射表
const GAN_ZHI_WUXING_MAP = {
    // 天干
    '甲': '木', '乙': '木',
    '丙': '火', '丁': '火',
    '戊': '土', '己': '土',
    '庚': '金', '辛': '金',
    '壬': '水', '癸': '水',
    // 地支
    '子': '水', '丑': '土',
    '寅': '木', '卯': '木',
    '辰': '土', '巳': '火',
    '午': '火', '未': '土',
    '申': '金', '酉': '金',
    '戌': '土', '亥': '水'
};

// 五行颜色映射
const WUXING_COLOR_MAP = {
    '木': 'wuxing-mu',
    '火': 'wuxing-huo',
    '土': 'wuxing-tu',
    '金': 'wuxing-jin',
    '水': 'wuxing-shui'
};


// ==================== 工具函数 ====================

/**
 * 获取五行对应的颜色类
 */
function getWuxingColorClass(wuxing) {
    return WUXING_COLOR_MAP[wuxing] || '';
}

/**
 * 获取天干地支对应的五行
 */
function getGanZhiWuxing(ganZhi) {
    return GAN_ZHI_WUXING_MAP[ganZhi] || '';
}

/**
 * 为表格单元格添加五行颜色
 */
function addWuxingColorToTableCells(element) {
    const cells = element.querySelectorAll('td');
    const wuxingStyles = {
        '木': { bg: 'linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%)', color: '#2d5016' },
        '火': { bg: 'linear-gradient(135deg, #ffebee 0%, #ffcdd2 100%)', color: '#b71c1c' },
        '土': { bg: 'linear-gradient(135deg, #efebe9 0%, #d7ccc8 100%)', color: '#5d4037' },
        '金': { bg: 'linear-gradient(135deg, #fff8dc 0%, #ffd700 100%)', color: '#b8860b' },
        '水': { bg: 'linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%)', color: '#0d47a1' }
    };
    
    cells.forEach(cell => {
        const text = cell.textContent.trim();
        for (const [wuxing, style] of Object.entries(wuxingStyles)) {
            if (text.includes(wuxing)) {
                cell.style.background = style.bg;
                cell.style.color = style.color;
                cell.style.fontWeight = 'bold';
                break;
            }
        }
    });
}

/**
 * 为表格添加滚动容器
 */
function wrapTablesWithScrollContainer(element) {
    const tables = element.querySelectorAll('table');
    tables.forEach(table => {
        if (table.parentElement.classList.contains('table-container')) return;
        
        const wrapper = document.createElement('div');
        wrapper.className = 'table-container';
        table.parentNode.insertBefore(wrapper, table);
        wrapper.appendChild(table);
    });
}

// ==================== UI更新模块 ====================

/**
 * 更新柱的显示（包含五行颜色）
 */
function updatePillar(pillarId, pillar, isDayPillar = false) {
    const element = document.getElementById(pillarId);
    if (!element) return;
    
    element.innerHTML = '';
    
    const ganContainer = document.createElement('div');
    ganContainer.className = 'bazi-ganzhi';
    if (isDayPillar) {
        ganContainer.classList.add('day-pillar-highlight');
    }
    
    const gan = document.createElement('span');
    gan.className = `bazi-gan ${getWuxingColorClass(pillar.天干五行)}`;
    gan.textContent = pillar.天干;
    gan.title = `${pillar.天干}（${pillar.天干五行}${pillar.天干阴阳}）`;
    
    const zhi = document.createElement('span');
    zhi.className = `bazi-zhi ${getWuxingColorClass(pillar.地支五行)}`;
    zhi.textContent = pillar.地支;
    zhi.title = `${pillar.地支}（${pillar.地支五行}${pillar.地支阴阳}）`;
    
    ganContainer.appendChild(gan);
    ganContainer.appendChild(zhi);
    element.appendChild(ganContainer);
}

/**
 * 更新五行标签显示
 */
function updateWuxing(elementId, ganWuxing, zhiWuxing) {
    const element = document.getElementById(elementId);
    if (!element) return;
    
    element.innerHTML = '';
    
    if (ganWuxing) {
        const ganSpan = document.createElement('span');
        ganSpan.className = `wuxing-tag ${getWuxingColorClass(ganWuxing)}`;
        ganSpan.textContent = ganWuxing;
        element.appendChild(ganSpan);
    }
    
    if (zhiWuxing) {
        const zhiSpan = document.createElement('span');
        zhiSpan.className = `wuxing-tag ${getWuxingColorClass(zhiWuxing)}`;
        zhiSpan.textContent = zhiWuxing;
        element.appendChild(zhiSpan);
    }
}

/**
 * 更新大运列表显示
 */
function updateDayunList(dayunList, dayunData) {
    dayunList.innerHTML = '';
    dayunData.forEach(dayun => {
        const item = document.createElement('div');
        item.className = 'list-item';
        item.innerHTML = `
            <span>${dayun.开始年龄}-${dayun.结束年龄}岁 (${dayun.开始年份}-${dayun.结束年份})</span>
            <span>${dayun.干支}</span>
        `;
        const detail = document.createElement('div');
        detail.className = 'list-detail';
        detail.textContent = `旬: ${dayun.旬} | 旬空: ${dayun.旬空}`;
        item.appendChild(detail);
        dayunList.appendChild(item);
    });
}

/**
 * 更新流年列表显示
 */
function updateLiunianList(liunianList, liunianData) {
    liunianList.innerHTML = '';
    if (liunianData && liunianData.length > 0) {
        liunianData.forEach(liunian => {
            const item = document.createElement('div');
            item.className = 'list-item';
            item.innerHTML = `
                <span>${liunian.年份}年 (${liunian.年龄}岁)</span>
                <span>${liunian.干支}</span>
            `;
            const detail = document.createElement('div');
            detail.className = 'list-detail';
            detail.textContent = `旬: ${liunian.旬} | 旬空: ${liunian.旬空}`;
            item.appendChild(detail);
            liunianList.appendChild(item);
        });
    } else {
        liunianList.innerHTML = '<div class="list-item">未显示流年信息</div>';
    }
}

/**
 * 创建五行徽章
 */
function createWuxingBadge(wuxing) {
    if (!wuxing) return '';
    const span = document.createElement('span');
    span.className = `wuxing-badge ${getWuxingColorClass(wuxing)}`;
    span.textContent = wuxing;
    return span;
}

/**
 * 创建带五行颜色的天干显示（包含阴阳）
 */
function createGanWithColor(gan, wuxing, yinyang) {
    if (!gan) {
        const span = document.createElement('span');
        span.textContent = '--';
        return span;
    }
    
    const container = document.createElement('span');
    
    // 天干文字（带五行颜色）
    const ganSpan = document.createElement('span');
    ganSpan.className = `gan-with-color ${getWuxingColorClass(wuxing)}`;
    ganSpan.textContent = gan;
    
    // 阴阳（小括号）
    const yinyangSpan = document.createElement('span');
    yinyangSpan.className = 'yinyang-inline';
    yinyangSpan.textContent = `（${yinyang || '--'}）`;
    
    container.appendChild(ganSpan);
    container.appendChild(yinyangSpan);
    
    return container;
}

/**
 * 创建带五行颜色的地支显示（包含阴阳）
 */
function createZhiWithColor(zhi, wuxing, yinyang) {
    if (!zhi) {
        const span = document.createElement('span');
        span.textContent = '--';
        return span;
    }
    
    const container = document.createElement('span');
    
    // 地支文字（带五行颜色）
    const zhiSpan = document.createElement('span');
    zhiSpan.className = `zhi-with-color ${getWuxingColorClass(wuxing)}`;
    zhiSpan.textContent = zhi;
    
    // 阴阳（小括号）
    const yinyangSpan = document.createElement('span');
    yinyangSpan.className = 'yinyang-inline';
    yinyangSpan.textContent = `（${yinyang || '--'}）`;
    
    container.appendChild(zhiSpan);
    container.appendChild(yinyangSpan);
    
    return container;
}

/**
 * 创建藏干显示（格式为"天干+五行"，带颜色，每个藏干一行）
 */
function createCangganDisplay(cangganArray) {
    if (!cangganArray || cangganArray.length === 0) {
        const span = document.createElement('span');
        span.textContent = '--';
        return span;
    }
    
    const container = document.createElement('div');
    container.className = 'canggan-container';
    
    cangganArray.forEach((gan) => {
        // 获取天干的五行
        const wuxing = getGanZhiWuxing(gan);
        
        // 创建天干+五行的显示，每个藏干一行
        const ganDiv = document.createElement('div');
        ganDiv.className = `canggan-item ${getWuxingColorClass(wuxing)}`;
        ganDiv.textContent = `${gan}${wuxing}`;
        
        container.appendChild(ganDiv);
    });
    
    return container;
}

/**
 * 创建数组元素的显示
 */
function createArrayDisplay(arr, isWuxing = false) {
    if (!arr || arr.length === 0) return '--';
    const container = document.createElement('div');
    arr.forEach((item, index) => {
        const itemSpan = document.createElement('span');
        if (isWuxing && typeof item === 'string') {
            // 如果是五行数组，添加徽章样式
            const badge = createWuxingBadge(item);
            itemSpan.appendChild(badge);
        } else {
            itemSpan.textContent = item;
            itemSpan.style.display = 'inline-block';
            itemSpan.style.margin = '2px';
        }
        container.appendChild(itemSpan);
    });
    return container;
}

/**
 * 更新八字详细信息表（竖排布局）
 */
function updateBaziDetailTable(result) {
    const tableContainer = document.getElementById('baziDetailTable');
    if (!tableContainer) return;
    
    tableContainer.innerHTML = '';
    
    const table = document.createElement('table');
    table.className = 'bazi-detail-table';
    
    // 表头 - 第一列为属性名，后面四列为四柱
    const thead = document.createElement('thead');
    const headerRow = document.createElement('tr');
    
    // 第一列：属性名称列（空表头）
    const firstHeader = document.createElement('th');
    firstHeader.textContent = '';
    headerRow.appendChild(firstHeader);
    
    // 四柱表头
    const pillars = [
        { name: '年柱', data: result.年柱 },
        { name: '月柱', data: result.月柱 },
        { name: '日柱', data: result.日柱 },
        { name: '时柱', data: result.时柱 }
    ];
    
    pillars.forEach(pillar => {
        const th = document.createElement('th');
        th.className = 'pillar-header';
        th.textContent = pillar.name;
        headerRow.appendChild(th);
    });
    
    thead.appendChild(headerRow);
    table.appendChild(thead);
    
    // 表体 - 每一行是一个属性，每一列是一柱
    const tbody = document.createElement('tbody');
    
    // 定义属性列表（移除了天干阴阳、地支阴阳、天干五行、地支五行这四行）
    const attributes = [
        { 
            name: '干支', 
            renderCell: (p, cell) => {
                cell.className = 'ganzhi-cell';
                cell.textContent = `${p.天干}${p.地支}`;
            }
        },
        { 
            name: '天干', 
            renderCell: (p, cell) => {
                const ganDisplay = createGanWithColor(p.天干, p.天干五行, p.天干阴阳);
                cell.appendChild(ganDisplay);
            }
        },
        { 
            name: '地支', 
            renderCell: (p, cell) => {
                const zhiDisplay = createZhiWithColor(p.地支, p.地支五行, p.地支阴阳);
                cell.appendChild(zhiDisplay);
            }
        },
        { 
            name: '纳音', 
            renderCell: (p, cell) => {
                cell.className = 'nayin-cell';
                cell.textContent = p.纳音 || '--';
            }
        },
        { 
            name: '藏干', 
            renderCell: (p, cell) => {
                cell.className = 'canggan-cell';
                const cangganDisplay = createCangganDisplay(p.藏干);
                cell.appendChild(cangganDisplay);
            }
        },
        { 
            name: '天干十神', 
            renderCell: (p, cell) => {
                cell.className = 'shishen-cell';
                cell.textContent = p.天干十神 || '--';
            }
        },
        { 
            name: '地支十神', 
            renderCell: (p, cell) => {
                cell.className = 'shishen-cell';
                cell.textContent = (p.地支十神 && p.地支十神.length > 0) ? p.地支十神.join('、') : '--';
            }
        },
        { 
            name: '地势', 
            renderCell: (p, cell) => {
                cell.className = 'dishi-cell';
                cell.textContent = p.地势 || '--';
            }
        }
    ];
    
    // 为每个属性创建一行
    attributes.forEach(attr => {
        const row = document.createElement('tr');
        
        // 第一列：属性名称
        const attrNameCell = document.createElement('td');
        attrNameCell.className = 'attr-name';
        attrNameCell.textContent = attr.name;
        row.appendChild(attrNameCell);
        
        // 后面四列：各柱的该属性值
        pillars.forEach(pillar => {
            const cell = document.createElement('td');
            attr.renderCell(pillar.data, cell);
            row.appendChild(cell);
        });
        
        tbody.appendChild(row);
    });
    
    table.appendChild(tbody);
    tableContainer.appendChild(table);
}

/**
 * 显示排盘结果
 */
function displayResult(result) {
    // 更新四柱八字
    updatePillar('yearPillar', result.年柱);
    updatePillar('monthPillar', result.月柱);
    updatePillar('dayPillar', result.日柱, true);
    updatePillar('hourPillar', result.时柱);
    
    // 更新四柱详情
    document.getElementById('yearDetail').textContent = `${result.年柱.天干}${result.年柱.地支} ${result.年柱.天干阴阳}${result.年柱.地支阴阳}`;
    document.getElementById('monthDetail').textContent = `${result.月柱.天干}${result.月柱.地支} ${result.月柱.天干阴阳}${result.月柱.地支阴阳}`;
    document.getElementById('dayDetail').textContent = `${result.日柱.天干}${result.日柱.地支} ${result.日柱.天干阴阳}${result.日柱.地支阴阳}`;
    document.getElementById('hourDetail').textContent = `${result.时柱.天干}${result.时柱.地支} ${result.时柱.天干阴阳}${result.时柱.地支阴阳}`;
    
    // 更新五行
    updateWuxing('yearWuxing', result.年柱.天干五行, result.年柱.地支五行);
    updateWuxing('monthWuxing', result.月柱.天干五行, result.月柱.地支五行);
    updateWuxing('dayWuxing', result.日柱.天干五行, result.日柱.地支五行);
    updateWuxing('hourWuxing', result.时柱.天干五行, result.时柱.地支五行);
    
    // 更新命主
    document.getElementById('mingzhu').textContent = `${result.日柱.天干}${result.日柱.天干五行}日主`;
    
    // 更新八字详细信息表
    updateBaziDetailTable(result);
    
    // 更新起运信息
    document.getElementById('qiyunInfo').textContent = result.起运;
    
    // 更新大运列表
    updateDayunList(document.getElementById('dayunList'), result.大运列表);
    
    // 更新流年列表
    updateLiunianList(document.getElementById('liunianList'), result.流年列表);
    
    // 更新命理分析文本
    const resultTextElement = document.getElementById('resultText');
    if (result.文本) {
        resultTextElement.innerHTML = marked.parse(result.文本);
        wrapTablesWithScrollContainer(resultTextElement);
        addWuxingColorToTableCells(resultTextElement);
    } else {
        resultTextElement.textContent = '请填写生辰信息后点击"开始排盘"按钮';
    }
}

// ==================== 数据生成模块 ====================

/**
 * 生成结构化数据（JSON格式）
 */
function generateJSONData(result) {
    return {
        基本信息: {
            性别: result.性别,
            生辰: result.生辰,
            八字: result.八字,
            日主: result.日柱 ? `${result.日柱.天干}${result.日柱.天干五行}` : null
        },
        四柱: {
            年柱: result.年柱,
            月柱: result.月柱,
            日柱: result.日柱,
            时柱: result.时柱
        },
        起运: result.起运,
        大运列表: result.大运列表,
        流年列表: result.流年列表
    };
}

/**
 * 生成适合大模型分析的格式化文本
 */
function generateAnalysisText(result, type = 'both') {
    if (!result) return '暂无排盘结果';
    
    const lines = [];
    
    if (type === 'markdown' || type === 'both') {
        if (result.文本) {
            lines.push(result.文本);
            if (type === 'both') {
                lines.push('', '---', '');
            }
        }
    }
    
    if (type === 'json' || type === 'both') {
        if (type === 'both') {
            lines.push('## 结构化数据（JSON格式）', '', '以下为 JSON 格式的结构化数据，便于程序化分析和处理：', '', '```json');
        }
        
        lines.push(JSON.stringify(generateJSONData(result), null, 2));
        
        if (type === 'both') {
            lines.push('```');
        }
    }
    
    return lines.join('\n');
}

// ==================== 主程序 ====================

document.addEventListener('DOMContentLoaded', function() {
    // DOM元素引用
    const inputSection = document.getElementById('inputSection');
    const inputSectionHeader = document.getElementById('inputSectionHeader');
    const calculateBtn = document.getElementById('calculateBtn');
    const loadingSpinner = document.getElementById('loadingSpinner');
    const buttonText = document.getElementById('buttonText');
    const errorMessage = document.getElementById('errorMessage');
    const copyTextButton = document.getElementById('copyTextButton');
    
    // 状态变量
    let isInputCollapsed = false;
    let currentResult = null;
    
    // ==================== 输入区域折叠/展开 ====================
    inputSectionHeader.addEventListener('click', function() {
        isInputCollapsed = !isInputCollapsed;
        inputSection.classList.toggle('collapsed', isInputCollapsed);
        inputSection.classList.toggle('expanded', !isInputCollapsed);
    });
    
    // ==================== 日期时间选择器初始化 ====================
    const datePicker = flatpickr("#datePicker", {
        locale: "zh",
        dateFormat: "Y-m-d",
        defaultDate: "2025-01-01",
        onChange: function(selectedDates) {
            const date = selectedDates[0];
            document.getElementById('year').value = date.getFullYear();
            document.getElementById('month').value = date.getMonth() + 1;
            document.getElementById('day').value = date.getDate();
        }
    });
    
    const timePicker = flatpickr("#timePicker", {
        locale: "zh",
        enableTime: true,
        noCalendar: true,
        dateFormat: "H:i",
        time_24hr: true,
        defaultDate: "12:00",
        onChange: function(selectedDates) {
            const date = selectedDates[0];
            document.getElementById('hour').value = date.getHours();
            document.getElementById('minute').value = date.getMinutes();
        }
    });
    
    // 设置初始值
    const initialDate = new Date();
    document.getElementById('year').value = initialDate.getFullYear();
    document.getElementById('month').value = initialDate.getMonth() + 1;
    document.getElementById('day').value = initialDate.getDate();
    document.getElementById('hour').value = 12;
    document.getElementById('minute').value = 0;
    
    if (timePicker.selectedDates.length > 0) {
        const timeDate = timePicker.selectedDates[0];
        document.getElementById('hour').value = timeDate.getHours();
        document.getElementById('minute').value = timeDate.getMinutes();
    }
    
    // ==================== 工具函数 ====================
    function setLoadingState(isLoading) {
        calculateBtn.disabled = isLoading;
        loadingSpinner.classList.toggle('show', isLoading);
        buttonText.textContent = isLoading ? '排盘中...' : '开始排盘';
    }
    
    function showError(message) {
        errorMessage.textContent = message;
        errorMessage.style.display = 'block';
    }
    
    function hideError() {
        errorMessage.style.display = 'none';
    }
    
    // ==================== 复制功能 ====================
    copyTextButton.addEventListener('click', function() {
        if (!currentResult) {
            alert('请先进行排盘');
            return;
        }
        
        const copyType = document.querySelector('input[name="copyType"]:checked').value;
        const textToCopy = generateAnalysisText(currentResult, copyType);
        
        const messages = {
            'markdown': '文本已复制到剪贴板（Markdown格式）',
            'json': '文本已复制到剪贴板（JSON格式）',
            'both': '文本已复制到剪贴板（Markdown + JSON格式）'
        };
        
        navigator.clipboard.writeText(textToCopy).then(
            () => alert(messages[copyType] || messages.both),
            (err) => alert('复制失败: ' + err)
        );
    });
    
    // ==================== 排盘功能 ====================
    calculateBtn.addEventListener('click', function() {
        // 获取输入值
        const calendarType = document.querySelector('input[name="calendarType"]:checked').value;
        const year = parseInt(document.getElementById('year').value);
        const month = parseInt(document.getElementById('month').value);
        const day = parseInt(document.getElementById('day').value);
        const hour = parseInt(document.getElementById('hour').value);
        const minute = parseInt(document.getElementById('minute').value) || 0;
        const second = parseInt(document.getElementById('second').value) || 0;
        const gender = document.querySelector('input[name="gender"]:checked').value;
        const sect = parseInt(document.querySelector('input[name="sect"]:checked').value);
        const showXiaoyun = document.querySelector('input[name="showXiaoyun"]:checked').value === 'true';
        const showYear = document.querySelector('input[name="showYear"]:checked').value === 'true';
        
        // 验证输入
        if (!year || !month || !day || hour === undefined) {
            showError('请填写完整的生辰信息！');
            return;
        }
        
        hideError();
        setLoadingState(true);
        
        console.log(`开始排盘: 性别${gender}；${year}-${month}-${day} ${hour}:${minute}:${second}`);
        
        setTimeout(() => {
            try {
                const result = 排盘(
                    gender,
                    {类型: calendarType, 年: year, 月: month, 日: day, 时: hour, 分: minute, 秒: second},
                    showXiaoyun,
                    showYear,
                    sect
                );
                
                currentResult = { ...result, 性别: gender };
                displayResult(result);
                setLoadingState(false);
                
                // 排盘后自动折叠输入区域
                if (!isInputCollapsed) {
                    inputSection.classList.add('collapsed');
                    inputSection.classList.remove('expanded');
                    isInputCollapsed = true;
                }
            } catch (error) {
                console.error('排盘错误:', error);
                showError('排盘过程中出现错误，请检查输入数据是否正确。');
                setLoadingState(false);
            }
        }, 0);
    });
});
